package com.zhiyou100.crm.servlet.department;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zhiyou100.crm.service.DepartmentService;
import com.zhiyou100.crm.service.impl.DepartmentServiceImpl;
import com.zhiyou100.crm.util.AdminBaseServlet;
import com.zhiyou100.crm.util.Department;
import com.zhiyou100.crm.util.Message;
import com.zhiyou100.crm.util.Pager;


@WebServlet(name = "DepartmentListServlet", urlPatterns = { "/department/list" })
public class ListServlet extends AdminBaseServlet {
	private static final long serialVersionUID = 1L;
	DepartmentService departmentService=new DepartmentServiceImpl();
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html; charset=UTF-8");
		List<Department> departments = departmentService.queryAll();
		if(departments!=null){
			//分页显示
			//初始页码
			int start = 1;
			int pagerNo=1;
			//页面大小，设置
			int pageSize = 3;
			//获取当前页码
			String currentPage1 = request.getParameter("pageNo");
			if (currentPage1 != null) {
				int currentPage2 = Integer.parseInt(currentPage1);
				pagerNo = currentPage2;
			}
			//总数据数，集合的大小
			int total = departments.size();
			//总页数
			int pageCount = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
			Pager pager = new Pager(total,pagerNo,pageSize,pageCount,start);
			List<Department> departments1=new ArrayList<>();
			for (int i = (pagerNo - 1) * pageSize; i < pagerNo * pageSize; i++) {
				if (i == departments.size()) {
					break;
				}
				departments1.add(departments.get(i));
			}
			request.setAttribute("pager", pager);
			request.setAttribute("departments", departments1);
//			request.setAttribute("departments",departments);
			request.getRequestDispatcher("/WEB-INF/view/department/list.jsp").forward(request, response);
		}else{
			System.out.println("出错了");
			response.sendRedirect(request.getContextPath()+"/list.jsp");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req,resp);
	}
}
